/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.yunji.framework_template.common.util.GeoUtils;
import com.yunji.framework_template.common.util.IPHelper;
import com.yunji.framework_template.orm.datasource.HandleDataSource;

/**
 * ClassName:CountryFilter <br/>
 * Date: 2018年10月25日 上午10:02:55 <br/>
 * 
 * @author fenglibin1982@163.com
 * @Blog http://blog.csdn.net/fenglibing
 * @version
 * @see
 */
public class CountryFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                                                                                              ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String countryCode = null;
        String defaultCountry = req.getParameter("defaultCountry");
        if (defaultCountry != null) {
            countryCode = defaultCountry;
        } else {
            /**
             * 根据用户访问的IP，获取用户所在的国家，如果是在多国家的应用中，后续会根据获取到的国家信息获取不同的数据源
             */
            String ipAddress = IPHelper.getIpAddr(req);
            countryCode = GeoUtils.getCountryCodeByIP(ipAddress);
        }
        HandleDataSource.putDataSource(countryCode);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
